package co.kr.bymin76.dipcalculator;

import android.app.Activity;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import co.kr.bymin76.common.PopupSpinner;
import co.kr.bymin76.controller.CalculatorController;
import co.kr.bymin76.controller.PreferenceController;
import co.kr.bymin76.model.ModelTitleValue;

public class DipCalculatorActivity extends Activity {
	
	private TextView txtCalculation;
	private TextView txtResult;
	private Double dpType = 1.5 ; 
	//숫자에 소수점 하나만 들어가게 하기 위해
	private Boolean pointChk = false;
	
	//입력 타임 
	private final Boolean LAST_INPUT_STRING = true;
	private final Boolean LAST_INPUT_NUMBER = false;

	private final int REQUEST_CODE_SPINNER_REGION = 0;
	
	private Boolean lastInputString = LAST_INPUT_STRING ;
	
	private String mCurrentRegionValue ;

	private Boolean reSet = false;
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        mCurrentRegionValue = readDip();
        
        txtCalculation = (TextView) findViewById(R.id.txt_calculation);
        txtResult = (TextView) findViewById(R.id.txt_result);
        
        
        Button btn0 = (Button) findViewById(R.id.btn_0); 
        Button btn1 = (Button) findViewById(R.id.btn_1); 
        Button btn2 = (Button) findViewById(R.id.btn_2); 
        Button btn3 = (Button) findViewById(R.id.btn_3); 
        Button btn4 = (Button) findViewById(R.id.btn_4); 
        Button btn5 = (Button) findViewById(R.id.btn_5); 
        Button btn6 = (Button) findViewById(R.id.btn_6); 
        Button btn7 = (Button) findViewById(R.id.btn_7); 
        Button btn8 = (Button) findViewById(R.id.btn_8); 
        Button btn9 = (Button) findViewById(R.id.btn_9); 
        Button btnPoint = (Button) findViewById(R.id.btn_point); 
        Button btnClear = (Button) findViewById(R.id.btn_clear); 
        Button btnBack = (Button) findViewById(R.id.btn_back); 
        Button btnDivsion = (Button) findViewById(R.id.btn_division); 
        Button btnMultiplication = (Button) findViewById(R.id.btn_multiplication); 
        Button btnSubtraction = (Button) findViewById(R.id.btn_subtraction); 
        Button btnAddition = (Button) findViewById(R.id.btn_addition); 
        Button btnResult = (Button) findViewById(R.id.btn_result); 
        Button btnDip = (Button) findViewById(R.id.btn_dip);
        
        btn0.setOnClickListener(clickListener);
        btn1.setOnClickListener(clickListener);
        btn2.setOnClickListener(clickListener);
        btn3.setOnClickListener(clickListener);
        btn4.setOnClickListener(clickListener);
        btn5.setOnClickListener(clickListener);
        btn6.setOnClickListener(clickListener);
        btn7.setOnClickListener(clickListener);
        btn8.setOnClickListener(clickListener);
        btn9.setOnClickListener(clickListener);
        btnPoint.setOnClickListener(clickListener);
        
        btnClear.setOnClickListener(clickListener);
        btnBack.setOnClickListener(clickListener);
        btnDivsion.setOnClickListener(clickListener);
        btnMultiplication.setOnClickListener(clickListener);
        btnSubtraction.setOnClickListener(clickListener);
        btnAddition.setOnClickListener(clickListener);
        btnResult.setOnClickListener(clickListener);
        btnDip.setOnClickListener(clickListener);
        
    }
    
	private OnClickListener clickListener = new OnClickListener() {
		
		public void onClick(View v) {
			// TODO Auto-generated method stub
			
			// �ڵ��ʱ�ȭ
			if (reSet){
				txtCalculation.setText("");
				reSet = false;
			}
			
			String tempStr = (String) txtCalculation.getText();
			
			switch (v.getId()) {

			case R.id.btn_0:
				if (lastInputString.equals(LAST_INPUT_NUMBER)){
					txtCalculation.setText(tempStr +"0");
				}else{
					txtCalculation.setText(tempStr +"0.");
					pointChk = true;
				}
				lastInputString = LAST_INPUT_NUMBER;
				break;

			case R.id.btn_1:
				txtCalculation.setText(tempStr+"1");
				lastInputString = LAST_INPUT_NUMBER;
				break;
				
			case R.id.btn_2:
				txtCalculation.setText(tempStr+"2");
				lastInputString = LAST_INPUT_NUMBER;
				break;
				
			case R.id.btn_3:
				txtCalculation.setText(tempStr+"3");
				lastInputString = LAST_INPUT_NUMBER;
				break;
				
			case R.id.btn_4:
				txtCalculation.setText(tempStr+"4");
				lastInputString = LAST_INPUT_NUMBER;
				break;
				
			case R.id.btn_5:
				txtCalculation.setText(tempStr+"5");
				lastInputString = LAST_INPUT_NUMBER;
				break;
				
			case R.id.btn_6:
				txtCalculation.setText(tempStr+"6");
				lastInputString = LAST_INPUT_NUMBER;
				break;
				
			case R.id.btn_7:
				txtCalculation.setText(tempStr+"7");
				lastInputString = LAST_INPUT_NUMBER;
				break;
				
			case R.id.btn_8:
				txtCalculation.setText(tempStr+"8");
				lastInputString = LAST_INPUT_NUMBER;
				break;
				
			case R.id.btn_9:
				txtCalculation.setText(tempStr+"9");
				lastInputString = LAST_INPUT_NUMBER;
				break;
				
			case R.id.btn_point:
				if (!lastInputString && !pointChk ){
					txtCalculation.setText(tempStr+".");
					pointChk = true;
				}
				break;
				
			case R.id.btn_clear:
				txtCalculation.setText("");
				txtResult.setText("");
				lastInputString = LAST_INPUT_STRING;
				pointChk = false;
				break;
				
			case R.id.btn_back:
				String lastString = "";
				
				int length = tempStr.length();
				if ( length > 0) {
					lastString = tempStr.substring(length-1,length);
					tempStr = tempStr.substring(0, length -1);
					txtCalculation.setText(tempStr);
					
					//소숫점을 삭제할 경우
					if (".".equals(lastString)) {
						pointChk = false;
					}
					//수식을 삭제할 경우
					if ( "×".equals(lastString) || "÷".equals(lastString) || "+".equals(lastString) || "-".equals(lastString) ){
						lastInputString = LAST_INPUT_NUMBER;
					}
					
				}
				
				if (tempStr.length() <= 0){
					lastInputString = LAST_INPUT_STRING;
					pointChk = false;
				}

				break;
				
			case R.id.btn_division:
			case R.id.btn_multiplication:
			case R.id.btn_subtraction:
			case R.id.btn_addition:
				if ( tempStr.length() > 0 ) {
					if (lastInputString.equals(LAST_INPUT_STRING)){
						tempStr = tempStr.substring(0, tempStr.length()-1);
					}
					switch (v.getId()) {
					
						case R.id.btn_division:
							txtCalculation.setText(tempStr+ getResources().getString(R.string.divsion));
							break;

						case R.id.btn_multiplication:
							txtCalculation.setText(tempStr+ getResources().getString(R.string.multiplication));
							break;

						case R.id.btn_subtraction:
							txtCalculation.setText(tempStr+ getResources().getString(R.string.subtraction));
							break;

						case R.id.btn_addition:
							txtCalculation.setText(tempStr+ getResources().getString(R.string.addition));
							break;
							
						default:
							break;
					}
					// 문자 입력 된 상태로 변경
					lastInputString = LAST_INPUT_STRING;
					
					// 다시 숫자를 사용해야 하니 소수점 표시 할수 있도록 상태 변경
					pointChk = false;
				}
				break;
				

			case R.id.btn_result:
				if (txtCalculation.getText().length() > 0 && lastInputString == LAST_INPUT_NUMBER){
					//계산기 컨트롤러
					CalculatorController result = new CalculatorController();
					
					//계산기 컨트롤러에 수식 셋팅
					result.setFormula((String)tempStr);
					
					//계산된 값 얻어오기
					txtCalculation.setText(result.getResult());
					String iiii;
					iiii = "";
				}else{
					Toast.makeText(getApplicationContext(),"수식을 완성해 주세요", Toast.LENGTH_LONG ).show();
				}
				break;
				
			case R.id.btn_dip:
				Double tempResult = 0.0;
				reSet = true;
				pointChk = false;
				if (txtCalculation.getText().length() > 0 && lastInputString == LAST_INPUT_NUMBER ) {
					
					String m = (String) txtCalculation.getText(); 

					// 계산이 안된 경우에는 계산기 컨트롤러에 넘긴다.
					if ( m.contains("×") || m.contains("÷") || m.contains("+") || m.contains("-") ){
						//계산기 컨트롤러
						CalculatorController result = new CalculatorController();
						
						//계산기 컨트롤러에 수식 셋팅
						result.setFormula((String)tempStr);
						
						//계산된 값 얻어오기
						txtCalculation.setText(result.getResult());
					}
					
					tempResult = Double.parseDouble( (String) txtCalculation.getText());
					tempResult = tempResult / dpType ;
					tempResult = Math.round(tempResult*10)/10.0;
					txtResult.setText( tempResult + "dp");
				}else{
					
					Toast.makeText(getApplicationContext(),getResources().getString(R.string.message_no_cal), Toast.LENGTH_LONG ).show();
				}
				break;
				
			default:
				break;
			}
			
		}
	};
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		
		switch (keyCode) {
			case KeyEvent.KEYCODE_MENU:
				String[] regionTitles = { "160", "180", "200", "220", "240", "260", "280", "300", "320", "340", "360", "380", "400" };
				String[] regionValues = { "160", "180", "200", "220", "240", "260", "280", "300", "320", "340", "360", "380", "400" }; 
				
				Resources myResource = getResources();
				String currentRegionTitle = myResource.getString(R.string.spinner_title);
				showSpinnerTheme( currentRegionTitle , myResource.getString(R.string.btn_ok), REQUEST_CODE_SPINNER_REGION, currentRegionTitle, mCurrentRegionValue, regionTitles, regionValues);
				break;
				
			case KeyEvent.KEYCODE_BACK:
				finish();
				break;
		}
		return super.onKeyDown(keyCode, event);
	}
	
	private void showSpinnerTheme(String title, String confirm, int requestCode, String currentTitle, String currentValue, String[] titles, String[] values) {
		
		Intent intent = new Intent(DipCalculatorActivity.this, PopupSpinner.class);
		intent.putExtra("title", title);
		intent.putExtra("confirm", confirm);
		intent.putExtra("current_title", currentTitle);
		intent.putExtra("current_value", currentValue);
		intent.putExtra("titles", titles);
		intent.putExtra("values", values);
		startActivityForResult(intent, requestCode);
		
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		if (resultCode == RESULT_OK) {
			if (requestCode == REQUEST_CODE_SPINNER_REGION) {
				ModelTitleValue titleValue = data.getParcelableExtra("title_value");
				PreferenceController controller = new PreferenceController();
				controller.saveDip(getApplicationContext(), "dip", titleValue.value);
				dpType = Double.parseDouble(titleValue.value) / 160;
				mCurrentRegionValue = titleValue.value;
			}
		}
		
		super.onActivityResult(requestCode, resultCode, data);
	}
	
	/**
	 * 설정된 dip 값을 읽어 온다
	 * @return
	 */
	private String readDip() {
    	PreferenceController controller = new PreferenceController();
    	String dip = controller.readDip(getApplicationContext(), "dip");
    	if ("".equals(dip))
    		dip = "240";
    	return dip;
    }
}